<?php

namespace App\Models\CacheModel\ai_chat_room;

use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class AiChatStoryLine extends BaseCache
{
    protected $table = 'ai_chat_room.ai_chat_story_line';

    protected $cacheModel = 'ai_chat_room.chat_story_line';

    /**
     * 保存数据
     * @param array $data
     * @return int
     */
    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        // 获取未删除 的数据
        $where = ['id' => ['in', $ids]];
        try
        {
            $data = $this->where($where)->column('*', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }


    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'chat_id', 'config_id', 'create_time']);
        }

        return $data;
    }

    /**
     * 获取 今天用户 更换剧情次数
     * @param int $uid
     * @return int
     * @throws \Exception
     */
    public function getChangeStoryLineNum(int $uid)
    {
        $date = date('Ymd');
        $changeStoryLineNum = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('change_story_line_num', "{$date}:{$uid}")
            ->getCache('num', 'change_story_line_num');

        return (int)$changeStoryLineNum;
    }

    /**
     * 添加用户更换剧情次数
     * @param int $uid
     * @param int $inc
     * @return void
     * @throws \Exception
     */
    public function storyLineChangeNumInc(int $uid, int $inc = 1)
    {   //  1天有效期
        $date = date('Ymd');
        CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('change_story_line_num', "{$date}:{$uid}")
            ->setCacheTime(86400)
            ->setCacheInc('num', 'change_story_line_num', $inc);
    }
}
